import React, { Component, Fragment } from 'react';
import { withRouter } from 'react-router-dom';
import { bus } from '../../utils/eventBus';
import { getGequurl } from '../../utils/api';
import './Play.css';

class Play extends Component {
	state = {
		// 播放列表
		playList: [],
		// 当前播放的url
		currentUrl: '',
		// bar宽度
		barWidth: '',
		// 当前时间
		currentTime: '0:00',
		// 当前播放索引
		currentPlayIndex: 0,
		// 是否是下一首
		isLoop: true,
		// 当前全部时间
		currentDuration: '0:00',
		// 是否显示播放列表
		isShowPlayListStyle: false,
		// 是否锁定
		isLock: false,
		// 是否正在播放
		isPlaying: false
	}
	componentDidMount () {
		// 进入mv页暂停播放
		bus.on('sypause', () => {
			if (this.audio !== null && this.audio.paused === false) {
				this.audio.pause();
				this.setState({
					isPlaying: false
				})
			}
		})
		// 离开mv页继续播放
		bus.on('syplay2', () => {
			if (this.audio !== null && this.audio.paused === true) {
				this.audio.play();
				this.setState({
					isPlaying: true
				})
			}
		})
		// 点击音乐播放
		bus.on('syplay', async (value) => {
			let result = await getGequurl(value.id);
			let narr;
			let song = result.data[0];
			let currentPlayIndex = 0;
			// 判断播放列表是否已有该歌曲 没有该歌曲才能进行添加播放列表并播放
			if (!this.state.playList.some((item) => item.id === value.id)) {
				// 准备播放数据
				let obj = {
					id: song.musicid,
					name: song.music_name,
					url: song.music_url == null ? "http://localhost:3001/" + song.music_file : song.music_url,
					artist: song.singer_name,
				}
				narr = [obj, ...this.state.playList];
			} else {
				// 已经在播放列表中
				currentPlayIndex = this.state.playList.findIndex((item) => item.id === value.id);
				narr = [...this.state.playList];
			}
			this.setState({
				currentUrl: song.music_url == null ? "http://localhost:3001/" + song.music_file : song.music_url,
				playList: narr,
				currentPlayIndex: currentPlayIndex,
				isPlaying: true,
			}, function () {
				this.audio.play();
			})
		})
	}
	// 设置播放栏常驻
	lock = () => {
		this.setState({
			isLock: !this.state.isLock
		})
	}
	// 音频播放时触发的事件 更新状态
	timeUpdate () {
		let { currentDuration } = this.state;
		var m = Math.floor(this.audio.currentTime % 3600 / 60);
		var s = Math.floor(this.audio.currentTime % 60);
		m = m < 10 ? "0" + m : m;
		s = s < 10 ? "0" + s : s;
		this.setState({
			barWidth: this.audio.currentTime * 100 / currentDuration + '%',
			currentTime: m + ':' + s
		})
	}
	// 暂停或播放
	playOrStop = () => {
		// 如果没有歌曲不能播放
		if (this.state.playList.length !== 0) {
			if (this.state.isPlaying === true) {
				this.audio.pause();
				this.setState({
					isPlaying: !this.state.isPlaying
				})
			} else {
				this.audio.play();
				this.setState({
					isPlaying: !this.state.isPlaying
				})
			}
		}
	}
	// 点击进度条 跳转到指定时间
	changeBar (e) {
		// 只有在音乐列表中有歌曲时才可以
		if (this.state.playList.length !== 0) {
			let { currentDuration } = this.state;
			var left = this.bar.offsetLeft + this.plays.offsetLeft;
			var barWidth = this.bar.offsetWidth;
			this.audio.currentTime = ((e.pageX - left) / barWidth) * currentDuration;
			this.setState({
				barWidth: this.audio.currentTime * 100 / currentDuration + '%',
			})
			if (!this.state.isPlaying) {
				this.setState({
					isPlaying: true,
				}, function () {
					this.audio.play();
				})
			}
		}
	}
	// 结束播放后进行的操作
	endPlay () {
		let { playList, currentPlayIndex, isLoop } = this.state;
		let currentIndex = currentPlayIndex + 1;
		// 循环下一首
		if (isLoop) {
			if (!(currentIndex >= playList.length)) {
				this.setState({
					currentUrl: playList[currentIndex].url,
					currentPlayIndex: currentIndex,
				}, function () {
					this.audio.play();
				})
			} else {
				this.setState({
					isPlaying: false
				})
			}
		} else {
			// 不是循环下一首 直接继续循环该曲播放
			this.setState({
				currentUrl: playList[currentPlayIndex].url,
				currentPlayIndex: currentPlayIndex
			}, function () {
				this.audio.play();
			})
		}
	}
	// 点击下一首或上一首
	preOrNext (index) {
		let { playList, currentPlayIndex, isLoop } = this.state;
		let currentIndex = currentPlayIndex + index;
		if (isLoop) {
			if (index === -1 && !(currentIndex < 0)) {
				this.setState({
					currentUrl: playList[currentIndex].url,
					currentPlayIndex: currentIndex,
				}, function () {
					this.audio.play();
				})
			} else if (index === 1 && !(currentIndex >= playList.length)) {
				this.setState({
					currentUrl: playList[currentIndex].url,
					currentPlayIndex: currentIndex,
				}, function () {
					this.audio.play();
				})
			}
		} else {
			if (index === -1 && !(currentIndex < 0)) {
				this.setState({
					currentUrl: playList[currentIndex].url,
					currentPlayIndex: currentIndex,
				}, function () {
					this.audio.play();
				})
			} else if (index === 1 && !(currentIndex >= playList.length)) {
				this.setState({
					currentUrl: playList[currentIndex].url,
					currentPlayIndex: currentIndex,
				}, function () {
					this.audio.play();
				})
			}
		}
	}
	// 切换循环类型
	changeLoop () {
		this.setState({
			isLoop: !this.state.isLoop
		})
	}
	// 显示音乐列表内容
	changePlayListShow () {
		this.setState({
			isShowPlayListStyle: !this.state.isShowPlayListStyle
		})
	}
	// 切换播放的歌曲
	changeCurrentPIndex (index) {
		let { playList } = this.state;
		this.setState({
			currentUrl: playList[index].url,
			currentPlayIndex: index,
			isPlaying: true
		}, function () {
			this.audio.play();
		})
	}
	// 删除播放列表中的某歌曲
	deleteC (index) {
		let { playList, currentPlayIndex } = this.state;
		let narr = playList;
		narr.splice(index, 1);
		if (index > currentPlayIndex) {
			this.setState({
				playList: narr
			})
		} else if (index < currentPlayIndex) {
			this.setState({
				playList: narr,
				currentPlayIndex: currentPlayIndex - 1
			})
		}
	}
	render () {
		let { isPlaying, isLoop, currentPlayIndex, isShowPlayListStyle, isLock, playList, currentDuration, currentUrl, currentTime, barWidth } = this.state;
		return (
			<Fragment>
				<audio onCanPlay={() => {
					this.setState({
						currentDuration: this.audio.duration
					})
				}} onEnded={() => { this.endPlay() }} onTimeUpdate={() => { this.timeUpdate() }} ref={c => this.audio = c} src={currentUrl} controls hidden></audio>
				<div onMouseEnter={() => { if (!isLock) { this.plays.style.bottom = '0'; } }} onMouseLeave={() => { if (!isLock) { setTimeout(() => { this.plays.style.bottom = '-80px'; }, 1500) } }} className='play' ref={c => this.plays = c} style={{ bottom: isLock ? '0' : '-80px' }}>
					<div title='点击常驻' onClick={this.lock} style={{ backgroundPosition: isLock ? '-95px -398px' : '-75px -398px' }} className='lock bg'></div>
					<div className='plays'>
						<div className='pre bg' title='上一首' onClick={() => { this.preOrNext(-1) }}></div>
						<div className='playing bg' title={isPlaying ? '暂停' : '播放'} style={{ backgroundPosition: isPlaying ? '-40px -165px' : '-40px -204px' }} onClick={this.playOrStop}></div>
						<div className='next bg' title='下一首' onClick={() => { this.preOrNext(1) }}></div>
					</div>
					<h2>{playList[currentPlayIndex] !== undefined ? '正在播放： ' + playList[currentPlayIndex].name + ' -- ' + playList[currentPlayIndex].artist : '暂无播放歌曲'}</h2>
					<div className='bar' ref={c => this.bar = c} onClick={(e) => this.changeBar(e)}>
						<div className='now' style={{ width: barWidth }}></div>
					</div>
					<div className='time'>{currentTime} / {currentDuration === '0:00' ? '0:00' : "0" + Math.floor((currentDuration) % 3600 / 60) + ':' + (Math.floor((currentDuration) % 60) < 10 ? '0' + Math.floor((currentDuration) % 60) : Math.floor((currentDuration) % 60))}</div>
					<div className='loop bg' title={isLoop ? '循环播放' : '单曲循环'} onClick={() => { this.changeLoop() }} style={{ backgroundPosition: isLoop ? '-32px -343px' : '-92px -343px' }} ></div>
					<div title='播放列表' className='playlist bg' onClick={() => { this.changePlayListShow() }}></div>
					<ul className='playlistul' style={{ display: isShowPlayListStyle ? 'block' : 'none' }}>
						{playList.length === 0 ? (<li>播放列表为空哦！</li>) : playList.map((item, index) => (
							<li className={currentPlayIndex === index ? 'active' : 'red'} title={item.name} key={item.id}><span className='index'>{index + 1}</span> &nbsp;<span onClick={() => { this.changeCurrentPIndex(index) }} className='text'>{item.name}</span><span className='del' onClick={() => { this.deleteC(index) }}>删除</span></li>
						))}
					</ul>
					<div className='comm' title='评论' onClick={() => {
						if (playList[currentPlayIndex] !== undefined) {
							this.props.history.push(`/index/songComment?id=${playList[currentPlayIndex].id}`);
						}
					}}></div>
				</div>
			</Fragment>
		)
	}
}

export default withRouter(Play);